Flash Article

Creating Movie Clip Subclasses in ActionScript 2.0

Brian Lesser
Ryerson University

ActionScript 2.0 makes it easy to create movie clips with predefined behaviors—even easier than it is using ActionScript 1.0. Not only do you not have to use the prototype object at all but the association between your class and a movie clip in the library is created by filling in a field in the authoring environment. This tutorial shows you how to write ActionScript 2.0 classes that define the behavior of movie clips in the library. It is based on my previous article "Creating Movie Clip Subclasses," which describes using ActionScript 1.0 in Macromedia Flash MX to do the same thing.

Just as my first tutorial shows you how to do a simple scripted animation and proceeds to a somewhat more complex puzzle game, this tutorial revisits the same animation and game using ActionScript 2.0. Everything I demonstrate here you can still do using ActionScript 1.0 in Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004. So what's different? The code in this tutorial is less cluttered and, in the case of the game, does a little more than the previous tutorial's code. Go ahead and skip ahead to the tutorials if you already know what I cover next. If you would like a little background information on movie clips and objects and how they relate to each other, then read on.

Requirements

To complete this tutorial you will need to install the following software and files:

Macromedia Flash MX 2004


or Macromedia Flash MX Professional 2004


Download sample files for this tutorial

Classes and Objects, Symbols and Clips

Movie clips exist as symbols in a movie's library. When a symbol in the library is placed on the Stage an instance of the symbol is created. During the life of the movie an instance may change its color, position, and other properties. The symbol in the library acts as a template or initial design for the clip. Once on the Stage, the instance itself can be changed using different techniques, including the following:

  • Animating the clip on the stage's timeline using motion tweens
  • Attaching behaviors or event handlers to the clip
  • Altering the clip's properties using ActionScript in a timeline

Whatever you do to each instance, the symbol in the library does not change; it remains as a template for creating other clips using ActionScript. Each instance of the symbol is unique in that it may have a particular state at one time. For example, one may be visible and another may not be.

ActionScript classes and objects have a similar, though somewhat different, relationship to each other as movie clip symbols and instances. An ActionScript class defines the initial data (properties) and behaviors (methods or functions) of an ActionScript object. Instead of creating a movie clip symbol in the library using drawing tools, an ActionScript class is created by writing some code called a class definition. Instead of dragging a symbol onto the Stage, an instance of an ActionScript class is created using the new keyword within a script.

In ActionScript 1.0 a definition for a class of objects is created using the prototype object. Here is a short example that shows the definition of a class and the creation of one object based on the class:

//Define the class in AS1 by defining a function:
function ScoreKeeperClass(nShapes){
   this.nShapes = nShapes;
   this.startTime = getTimer();
   this.hits = 0;
}

// Give the class methods by attaching functions to the prototype object.
ScoreKeeperClass.prototype.addHit = function(){
   this.hits++;
}

ScoreKeeperClass.prototype.getScore = function(){
   return this.hits/this.nShapes;
}

// Create an object of the class using the new keyword.
scoreKeeper = new ScoreKeeperClass(10);

// Call some methods of the object.
scoreKeeper.addHit();
scoreKeeper.addHit();
trace("Your score is: " + scoreKeeper.getScore()); // Your score is: 0.2
    

Of course, other than printing something into the output window, this snippet of code just manipulates some data inside a score keeper object.

ActionScript 2.0 classes and objects are similar except that a class file containing slightly different code defines the class. For example, in a file named ScoreKeeper.as you might have this code:

// Define the class using the class keyword.
class ScoreKeeper{
   
   // Define the properties of the class including their type.
   var hits:Number = 0;
   var startTime:Number;
   var nShapes:Number;
   
   // Define a constructor function to be called when a new object is created.
   function ScoreKeeper(n){
      nShapes = n;
      startTime = getTimer();
   }
   
   // Define some methods/functions for each object of this class.
   function addHit(){
      hits++;
   }
   
   function getScore(){
      return hits/nShapes;
   }
}
    

To use this class you have these statements on the Timeline of your movie:

scoreKeeper = new ScoreKeeper(10);
scoreKeeper.addHit();
scoreKeeper.addHit();
trace("Your score is: " + scoreKeeper.getScore()); // Your score is: 0.2
    

ActionScript objects are instances of ActionScript classes, much as movie clips on the Stage are instances of movie clip symbols in the library. After an ActionScript object is created its properties (data) may change over time just as the properties of a movie clip may change. The important difference between classes and movie clip symbols is that classes give objects a predefined set of behaviors that every object of that class will have. For example, every ScoreKeeper object will have the custom written getScore() method. Even in Macromedia Flash 5 there was no simple way—like defining methods—to create predefined behaviors for a movie clip symbol.

A Short History of Movie Clip Behaviors

Macromedia Flash 5 was a wonderful step forward for people who wanted to write ActionScript to control movie clips in a Flash movie. Although it was possible to write complex ActionScript event handlers for individual movie clips, it was cumbersome to create a movie clip symbol in the library that you could just drop on the Stage with predefined behaviors. For example, to make a movie clip do something before the next frame appears, an onClipEvent handler can be attached directly to the clip on the Stage:

onClipEvent(enterFrame){
   _x += 10; // Move the clip ten pixels to the right between each frame.
}
    

In Macromedia Flash 5 you had to nest movie clips inside other movie clips to give them predefined behaviors. For example, if you wanted to drag a movie clip of a ball onto the Stage that was already preprogrammed to bounce around the Stage, the ball clip's symbol in the library had to contain another clip (often referred to as a controller or process clip) with the necessary bouncing behaviors attached to it. While essential in Flash 5, these clips littered the library and distributed the movie's code in often hard-to-find places.

Macromedia Flash MX removed this need for embedding clips within movie clips. As an alternative, it made it possible to create types of ActionScript objects (classes) that were subclasses (or derived from) the MovieClip object. ActionScript objects that were subclasses of the MovieClip object could define method handlers for movie clip events, such as entering a frame or being loaded prior to becoming visible for the first time (onEnterFrame and onLoad methods), and could manipulate movie clip properties, such as _alpha, as though they were regular object properties. Once a movie clip subclass is defined in ActionScript, it can be associated with a movie clip symbol in the library. A big advantage to this approach—aside from getting rid of unnecessary inner clips—is that the movie clip code could be found in one of a few easy-to-check locations:

  • The first frame of the main Timeline of a movie
  • The main Timeline of the movie clip
  • An external ActionScript file included in the published movie

The basic process in Macromedia Flash MX for creating a set of behaviors for a movie clip symbol looked like this: You first create a particular class in ActionScript. You then define how movie clips associated with that class will behave by adding event handlers to the class definition. Finally, you connect your class with a particular movie clip by "registering" the class with the movie clip's linked identifier in the library. Once this process is complete, your class and its event handlers are automatically associated with every instance of the movie clip created afterwards.

Here is a short ActionScript 1.0 code snippet that doesn't do anything more than move the clip 10 pixels to the right between frames:

function Ball(){
}
Ball.prototype = new MovieClip();
Object.registerClass("Ball", Ball);

Ball.prototype.onEnterFrame = function(){
	this._x += 10;
}
    

The onEnterFrame method of the Ball class provides a custom behavior for the movie clip that you would otherwise have to write into an onMovieClip(enterFrame) handler attached to an actual clip.

ActionScript 2.0 allows you to do the same thing you can do in ActionScript 1.0. However, class definitions are simpler to write. Instead of using the prototype object, you can almost completely dispense with the keyword this and organize your source code in one area: a series of well organized ActionScript 2.0 class files. Here is the previous code snippet rewritten in ActionScript 2.0:

dynamic class Ball extends MovieClip {
   function onEnterFrame() {
      _x += 10;
   }
}

Tutorial 1: Using a Movie Clip Subclass to Make a Bouncing Ball Animation

This tutorial shows you how to create an animation (displayed below) that contains multiple instances of one bouncing-ball movie clip.

Each instance of the movie clip contains a different message and has a different opacity; one is even scaled larger than the others. Despite these variations, you can see that the movie clip instances still exhibit the same behavior. They each appear in a random place, move off in a random direction, and correctly bounce off the edge of the Stage.

Before you begin the tutorial, you should have an overall view of the basic steps I will cover:

  1. Create a movie clip named Ball.
  2. Set the linkage properties of the Ball clip to export it for use by ActionScript and associate it with the ActionScript 2.0 Ball class
  3. .
  4. Create an ActionScript class named Ball in a file named Ball.as that extends the MovieClip class.
  5. Write a constructor function to initialize each clip when it is created and an onEnterFrame event handler method to set the new position for the ball when a new frame is about to appear.
  6. In the first frame of the main Timeline of the movie use the attachMovie function to add as many instances of the Ball movie clip to the Stage as you want. Use the initObject parameter to give each Ball movie clip unique property values like size, message, and opacity.

Step 1: Create the Movie Clip

Create a new Flash movie and save it in a new directory. Choose Insert > New Symbol in the main menu. In the Create New Symbol dialog box, name the movie clip Ball. In the Behavior section, select the Movie Clip option and click OK. To follow this tutorial, draw a ball shape or your own graphic. The graphic must be centered on the registration point. In this example, the graphic is composed of layers of simple circle drawings. The top two are semitransparent and contain a radial gradient fill; the bottom layer contains a simple circle with a flat color.

Next add a text field on top of the movie clip graphic (see Figure 1). I happened to use the text letter A. With the text field selected, verify on the Property inspector that Text Type is set to Dynamic Text. In the Var text box, type msg. This ties the text field to a variable.

Note: The initial text in the text field is just for sizing and will not appear when each instance of the Ball movie clip is attached to the movie. Also, the height and width of the text field is less than the height or width of the ball.

Creating the Ball movie clip.

Figure 1. Creating the Ball movie clip.

Step 2: Set the Linkage Properties of the Ball Clip

After creating the visual parts of the movie clip, associate it with the ActionScript 2.0 Ball class by right-clicking (Windows) or Command-clicking (Macintosh) the movie clip's name in the library. In the context menu, select Linkage. This opens the Linkage Properties dialog box (see Figure 2). Click the Export for ActionScript option and type Ball in the AS 2.0 Class field. Make sure Identifier is also named Ball and that the Export in First Frame option is also selected. Click OK.

Associating the Ball movie clip with the Ball class.

Figure 2. Associating the Ball movie clip with the Ball class.

Step 3: Creating the Ball Class

Now that you've properly identified the movie clip and associated it with an ActionScript 2.0 class it's time to create the Ball class. Save the Ball class in a separate text file named Ball.as. You can use any text editor to create and edit the file or else you can use Macromedia Flash MX 2004 or Macromedia Flash MX Professional 2004. If you use either edition of Flash, select File > New > ActionScript File. When you see the untitled script editing pane choose File > Save As and save the empty file in the same directory as your FLA file. Make sure you name the script file Ball.as.

Now define the ActionScript Ball class. Type the following into the file and save it again:

dynamic class Ball extends MovieClip {

}
    

This short bit of code defines a new class that is a subclass of the MovieClip class. Making it a MovieClip subclass means that it can manipulate all the properties of any Ball movie clip and also define event handling methods for all the events a movie clip receives. Reading from left to right, here is what the words in this short class definition mean:

  • dynamic: Indicates that each Ball object can have new methods and properties created for it at any time. They do not have to be defined in the class definition. Movie clips are dynamic and therefore so are classes that subclass (or extend) them.
  • class: Says that you are defining a class of objects that will all get their behavior from this class definition.
  • Ball: The name of the class.
  • extends: If the class is based on another class, and therefore inherits all the properties and methods of the base class, the extends keyword is used.
  • MovieClip: The name of the class being extended.

Step 4: Coding the Ball Class

So far, the class definition in your ActionScript file doesn't do anything. You need to have your class do two things: It needs to initialize itself by doing things like choosing an initial place to appear on the Stage and it needs to respond to enterFrame events so that it can move itself to its next position on the Stage before the next frame of the movie appears:

dynamic class Ball extends MovieClip {

   function Ball() {
   }
   
   function onEnterFrame() {
   }

}
    

Initializing the Class with a Constructor Function: Within the Ball class definition a function named Ball is also defined. Because the function has the same name as the class it will be called each time a Ball object is created. The function is therefore called a constructor function and it is normally used to initialize the object before it is used.

Event Handlers: Every movie clip subclass inherits the ability to define methods to receive (or handle) movie clip events. The method names are named after the events. In this example, an onEnterFrame method is defined and called just before the clip appears in each new frame of the movie. It plays the same role as manually attaching an onClipEvent(enterFrame) handler to a movie clip on the Stage.

The Ball Constructor Function in Detail: The Ball constructor function does three things:

  • Determine how far in the x and y axis the clip's registration point can travel before it has to bounce back into the Stage
  • Position the clip at a random location within the safe travel zone for the clip's registration point
  • Generate a random amount to move the clip along the x and y axis between frames (x velocity and y velocity)

Here is the actual code for the Ball constructor function:

function Ball() {
   // Calculate the limits of travel for this clip's registration point.
   xMin = _width/2;
   yMin = _height/2;
   xMax = Stage.width  - xMin;
   yMax = Stage.height - yMin;
   
   // Determine the random starting position within the Stage for this clip.    
   _x = Math.floor(Math.random()*(Stage.width  - _width))  + xMin;
   _y = Math.floor(Math.random()*(Stage.height - _height)) + yMin;
   
   // Generate random x and y velocities for each instance of this clip.
   xVel = Math.floor(Math.random() * 25) - 10;
   yVel = Math.floor(Math.random() * 25) - 10;
}

    

Two things are worth noting about how this particular constructor function works. One is that, unlike in ActionScript 1.0, it uses the _width, _height, _x, and _y properties of the movie clip without having to add the keyword this.

Instead of:

xMin = this._width/2;

You can just write:

xMin = _width/2;

This is a feature of ActionScript 2.0. Also this is not required to assign values to other properties of the object. In this code, xMin, xMax, yMin, yMax, xVel, and yVel are all properties of each Ball object. However, to make them properties you either need to declare them within the class definition or return to using the this keyword. Since you have to declare object properties you might as well take advantage of ActionScript 2.0's strong typing feature and declare what type of value each variable may contain. This snippet of code shows the declarations, and where to put them, within the Ball class definition:

dynamic class Ball extends MovieClip {

   // Travel limits for the movie clip's registration point.
   var xMin:Number, yMin:Number, xMax:Number, yMax:Number;
   // Velocity in x and y for the movie clip.
   var xVel:Number, yVel:Number;
   // Variable set in attachMovie and used by the text field.
   var msg:String;

   function Ball() {
   }
   
   function onEnterFrame() {
   }
}

    

The onEnterFrame Method in Detail: The onEnterFrame method calculates the next position for the movie clip and checks to make sure it is within the movie clip's travel limits. If it is not, the position of the registration point is recalculated as though it has just bounced off the edge of the Stage. The x and y position of the registration point are calculated separately:

function onEnterFrame() {
   /// Get the x and y positions for the next frame.
   var nextX = xVel + _x;
   var nextY = yVel + _y;
   
   // Make sure the registration point is within limits.
   if (nextX > xMax) {
      // Change direction by changing the sign of xVel.
      xVel = xVel * -1;
      // Bring clip back by the amount it has overshot its limit.
      nextX = this.xMax - (nextX - xMax);
   } else if (nextX < xMin) {
      xVel = xVel * -1;
      nextX = xMin + (xMin - nextX);
   }
   if (nextY > yMax) {
      yVel = yVel * -1;
      nextY = yMax - (nextY - yMax);
   } else if (nextY < yMin) {
      yVel = yVel * -1;
      nextY = yMin + (yMin - nextY);
   }
   
   // Now that we are sure the position in nextX and nextY are correct, 
   // set the position for the next frame.
   _x = nextX;
   _y = nextY;
}
    

Finally, here is the entire code in the Ball.as file, complete with comments:

/**
 * The Ball class extends the dynamic MovieClip class and is therefore also
 * dynamic. The Ball class assumes a MovieClip in the library is associated with
 * this class. 
 */
dynamic class Ball extends MovieClip {
   // Travel limits for the movie clip's registration point.
   var xMin:Number, yMin:Number, xMax:Number, yMax:Number;
   // Velocity in x and y for the movie clip.
   var xVel:Number, yVel:Number;
   // Variable set in attachMovie and used by the text field.
   var msg:String;

   /** 
    * The Ball constructor function calculates the bounding rectangle
    * within which this clip's registration point is allowed to travel.
    * The clip's registration point is assumed to be in the center of the 
    * clip but the height and width of the clip do not have to be the same.
    * Therefore the bounding rectangle is calculated for each clip when
    * each clip's constructor is called. 
    * The Stage object provides Stage.width and Stage.height.
    * A random starting position and random velocity are also determined.
    */
   function Ball() {
      // Calculate the limits of travel for this clip's registration point.
      xMin = _width/2;
      yMin = _height/2;
      xMax = Stage.width  - xMin;
      yMax = Stage.height - yMin;
      
      // Determine the random starting position within the Stage for this clip.    
      _x = Math.floor(Math.random()*(Stage.width  - _width))  + xMin;
      _y = Math.floor(Math.random()*(Stage.height - _height)) + yMin;
      
      // Generate random x and y velocities for each instance of this clip.
      xVel = Math.floor(Math.random() * 25) - 10;
      yVel = Math.floor(Math.random() * 25) - 10;
   }
   
   /**
    * The onEnterFrame method calculates the next position for the movie clip
    * and then checks to make sure it is within the movie clip's travel limits.
    * If it is not the position of registration point is recalculated as though
    * it has just bounced off the edge of the stage. The x and y position of the
    * registration point are calculated separately.
    */
   function onEnterFrame() {
      /// Get the x and y positions for the next frame.
      var nextX = xVel + _x;
      var nextY = yVel + _y;
      
      // Make sure the registration point is within limits.
      if (nextX > xMax) {
         // Change direction by changing the sign of xVel.
         xVel = xVel * -1;
         // Bring clip back by the amount it has overshot its limit.
         nextX = xMax - (nextX - xMax);
      } else if (nextX < xMin) {
         xVel = xVel * -1;
         nextX = xMin + (xMin - nextX);
      }
      if (nextY > yMax) {
         yVel = yVel * -1;
         nextY = yMax - (nextY - yMax);
      } else if (nextY < yMin) {
         yVel = yVel * -1;
         nextY = yMin + (yMin - nextY);
      }
      
      // Now that we are sure the position in nextX and nextY are correct, 
      // set the position for the next frame.
      _x = nextX;
      _y = nextY;
   }
}
    

Step 5: Attaching Instances of the Movie Clip to the Stage

To attach a movie clip to the Stage and initialize it in Macromedia Flash 5 you write code like this:

attachMovie("Ball", "b0", 100);
mc = eval("b0");
mc.msg = "Hi";
mc._alpha = 50;
    

The first line attaches the movie clip in the library with the linkage identifier "Ball" to the Stage, gives it an instance name of "b0", and sets its stacking level at 100. The next line uses the eval() function to make the mc variable a reference to the "b0" instance of the clip. The last two lines use the reference in mc to set the initial properties of the movie clip.

You can still do the same thing in Flash MX and Flash MX 2004 even though the eval() function is no longer necessary:

mc = attachMovie("Ball", "b0", 100);
mc.msg = "Hi";
mc._alpha = 50;
    

However, this doesn't let you feed information to your constructor function. That's because the constructor function is called when attachMovie() is called. The msg and _alpha properties of the object will be changed after the constructor is called. To pass information to the constructor function you need to use the initObject parameter of the attachMovie() method.

Here's a one-line example that does the same thing as the three or four statements above:

attachMovie("Ball", 'b0', 100, {msg: 'Hi', _alpha: 50});

This use of attachMovie() is the same as the first line in the previous Flash 5 example, except that an additional parameter became available with Flash MX in the attachMovie() function. In the documentation, this is called an initObject, which contains initial values that populate the object before the constructor function is called. (Anyone familiar with object-oriented programming can think of this as similar to providing parameters to a movie clip constructor function.) There are other ways to write this but the curly brackets are probably the simplest. The following expression creates an object with two properties: msg and _alpha. The values for these properties follow the colon after each property's name:

{msg: 'Hi', _alpha: 50}

You can place the following code on the first frame of the main Timeline of the movie. It creates three instances of the Ball movie clip, each of which contains a different message and has a different _alpha value. The last one is twice as large as the previous two because the _xscale and _yscale values are also set:

attachMovie("Ball", 'b0', 102, {msg: 'Hi', _alpha: 50});
attachMovie("Ball", 'b1', 101, {msg: 'Bye', _alpha: 80});
attachMovie("Ball", 'b2', 100, {msg: 'Big', _alpha: 100, 
                                _xscale: 200, _yscale: 200});
    

Note that in the third instance, the size of the movie clip will be different; this is reflected in different _width and _height values in the constructor function.

If you don't want to use an initObject as shown here and prefer to use this type of code instead:

mc = attachMovie("Ball", "b0", 100);
mc.msg = "Hi";
mc._alpha = 50;
    

Create an onLoad() method and move your initialization code from your constructor function into your onLoad() method. The onLoad() method will be called after the msg and _alpha properties are set.

In summary, you can associate movie clip symbols with ActionScript 2 classes. When a clip is created an ActionScript object is created and its constructor is called. When movie clip events occur, the ActionScript object associated with the instance of the movie clip symbol responds. Using ActionScript 2.0, you can write classes more easily and safely (with strong typing) than you could in ActionScript 1.0. It's also easier to write larger and more complex applications. Whether you use ActionScript 1.0 or 2.0, associating a class with a symbol in the library is the best way to give a movie clip symbol predefined behaviors.

In the next tutorial, you pick up the pace to create a more complicated grab-and-match-the-shapes game.

Tutorial 2: Creating a More Extensive Grab-and-Match Puzzle

Watching balls bounce around the Stage (even if each one is a little different) isn't that exciting—at least not for very long. This tutorial uses the same techniques demonstrated in the previous tutorial but takes them a little farther to create a simple game. In this game, the player must capture a puzzle piece shape that's bouncing around one area and drag it to the identical white shape in another area. You can play the game (and download the tutorial's FLA and class files from the first page).

This game is slightly more elaborate than the one originally presented in the ActionScript 1.0 version of this article. It uses a more object-oriented approach, changes the color of the piece when a player successfully grabs it, randomizes the position of each piece in the drop zone area, and lets the player quit without completing the entire game.

In order to minimize the size of the SWF file, I only created one graphic symbol for each shape. The shapes are loaded dynamically into two different types of movie clips when the clips are attached to the Stage. The PuzzlePiece movie clip provides the drag-and-drop and bouncing-around behaviors. The DropZone movie clip is a convenient target movie clip. Each PuzzlePiece clip has a matching DropZone clip containing the same shape on which the player must drop it. If you look at these two movie clips in the library, you see that they are really just empty movie clips; they contain no code or graphics. In fact, the only reason they are in the library at all is so that there will be movie clips available with the PuzzlePiece and DropZone linkage identifiers. The appearance of these clips comes from attaching graphic symbols to the movie clips when each movie clip is attached to the movie. The event handlers for the movie clip come from the ActionScript in the class files for the PuzzlePiece and DropZone classes.

The symbols in the library are simple, single-layer graphics drawn in white and named pGraphic1, pGraphic2, and so on. Each one has a linkage identifier in the same format. You can find them all in the Graphics folder in the library.

There are two other movie clips worth mentioning here. One is a simple white rectangle movie clip manually placed on the Stage and given the instance name bounceBox. This clip defines the area in which the PuzzlePiece movie clips are allowed to bounce around. The DropBar movie clip was also manually placed on the Stage to provide a black background area for the white DropZone clips.

The DropZone Movie Clips

If you look at the DropZone movie clip in the library you see that it contains no graphics or script. The clip gets its appearance and behaviors by executing methods of the ActionScript DropZone class defined in the DropZone.as file. If you check the linkage properties of the DropZone movie clip in the library you'll see something like Figure 3.

The DropZone movie clip is associated with the DropZone class.

Figure 3. The DropZone movie clip is associated with the DropZone class.

Each DropZone clip acts as a target clip for one of the PuzzlePiece clips. When a DropZone clip is attached to the movie (using the global attachMovie() function) it is passed a number that it uses to attach the right pGraphic symbol from the library to itself. A matching PuzzlePiece is given the same number and uses the same graphic. Note that the attachMovie() method of the movie clip attaches the pGraphic to the clip, not the global attachMovie() function. Calling attachMovie() within a MovieClip subclass definition calls the attachMovie method; you don't need to prepend this to it. Doing this loads that graphic into the DropZone movie clip rather than into the movie. The movie clip's method is called, instead of the global function, because attachMovie() is being called from within the DropZone class.

Here is the complete code for the DropZone class. Please take a minute to read through it:

dynamic class DropZone extends MovieClip {

   // Parameter passed in by attachMovie in the initObject.
   var gNumber:Number;
   
   /**
    * The DropZone constructor gets one of the graphics from the library named 
    * pGraphic1 through pGraphic13 and attaches it to this movie clip.
    */
   function DropZone() {
      attachMovie("pGraphic" + gNumber, "graphic" , 100);     
   }
   
   /**
    * The fadeOut method is called when a matching Puzzle Piece is dropped 
    * on this DropZone clip and calls this clip's fadeOut() method.
    * fadeOut sets the onEnterFrame handler for this clip to an anonymous function 
    * that fades out the clip and then removes it altogether once it 
    * is transparent.
    */
   function fadeOut() {
      onEnterFrame = function () {
         _alpha -= 10;
         if (_alpha <= 0) {
            removeMovieClip(this);
         }
      };
   }
}

    

The DropZone class is not long and complex. Aside from attaching the right shape symbol in the library in order to give itself a visible shape, it only includes one method. A PuzzlePiece clip calls the DropZone's fadeOut() method if it discovers that the player has dropped it on its target DropZone clip. Just as with the earlier Ball class, the DropZone class extends the MovieClip class so that it can be tied to a DropZone clip instance on the Stage, manipulate movie clip properties, and receive movie clip events.

The Puzzle Pieces

The PuzzlePiece movie symbol is also an empty clip in the library. Each PuzzlePiece clip on the Stage gets its appearance and behavior by executing code that's part of the PuzzlePiece class definition in the PuzzlePiece.as file. The PuzzlePiece class is the most complicated class in the game but when you look at the code you see that it is similar in many respects to the Ball class from the previous tutorial. Like the Ball class, the PuzzlePiece class constructor does the following:

  • It determines the travel limits of the puzzle piece, but this time within a bounceBox movie clip. A reference to the bounceBox clip is passed into the PuzzlePiece constructor in an initObject.
  • It determines an initial random position within the bounceBox and a random direction and velocity in which to travel.

Like the Ball class, the onEnterFrame() method of the PuzzlePiece class moves the puzzle piece inside the bounceBox clip.

The PuzzlePiece class is different than the Ball class because it allows the player to drag the clip around the Stage. If the player drops the clip on top of the matching DropZone, the PuzzlePiece tells the matching DropZone clip to fade out, tells the scoreKeeper object to count a hit, and then disposes of itself. The matching DropZone clip and scoreKeeper objects must be passed into each PuzzlePiece in an initObject when the PuzzlePiece is attached to the movie. The code that does this is shown later.

Here is the complete code for the PuzzlePiece class. Please spend a few minutes reading through it (it's been extensively commented):

/**
 * The PuzzlePiece class provides all the prebuilt behaviors and 
 * additional properties needed by a PuzzlePiece movie clip to:
 *   1. Position itself randomly within a the bounceBox movie clip 
 *      and move randomly within it.
 *   2. Allow the clip to be dragged around the stage.
 *   3. Detect if it has been dropped on its targetClip and tell the 
 *      scoreKeeper object if it has.
 *
 * This class is designed for use when the PuzzlePiece clip is attached 
 * to the movie by calling attachMovie and must be passed the following 
 * parameters in the initObject:
 *   1. bounceBox – a reference to a movie clip that this clip must bounce within.
 *   2. gNumber – the number of the graphic in the library to load into this clip.
 *   3. targetClip – a DropZone clip this clip is supposed to be dropped on.
 *   4. scoreKeeper – a reference to an ActionScript object so this clip can 
 *      report that it has been dropped on its targetClip.
 *
 * Version: 2
 * Author: Brian Lesser
 */

dynamic class PuzzlePiece extends MovieClip {
   /////// Properties of this movie clip subclass 
   // Color object used to change the color of this clip's graphic:
   var gColor:Color;
   // Travel limits in x and y for this clip's registration point:
   var xMin:Number, xMax:Number, yMin:Number, yMax:Number;
   // x and y velocity (number of pixels to move in x and y between frames):
   var xVel:Number, yVel:Number;
   // Flag to keep track if the clip is being dragged:
   var dragging:Boolean = false;
   
   /////// Properties of this movie clip subclass 
   /////// passed in from the initObject.
   // Movie clip that defines the travel limits of the clip when bouncing around:
   var bounceBox:MovieClip; 
   // Graphic number in the library of the graphic to load into this clip:
   var gNumber:Number;
   // Target clip that this clip should be dropped on:
   var targetClip:MovieClip;
   // The score keeper object that records hits:
   var scoreKeeper:ScoreKeeper;

   /**
    * The PuzzlePiece Constructor sets up the clip's appearance, travel limits,
    * initial position and velocity.
    */
   function PuzzlePiece() {
      //Attach the graphic shape to this clip:
      var graphic = attachMovie("pGraphic" + gNumber, 'graphic', 100);
   
      //Make everything a grey/blue color to start:
      gColor = new Color(graphic);
      gColor.setRGB(0x443377); 
      
      // Determine the bounding limits for the registration point 
      // within the bounceBox clip:
      var halfWidth  = _width/2;
      var halfHeight = _height/2;
      xMin = bounceBox._x + halfWidth;
      yMin = bounceBox._y + halfHeight;
      xMax = xMin + bounceBox._width  – _width;
      yMax = yMin + bounceBox._height – _height;  
      
      //Select a random position within the bounceBox clip to show up in:
      _x = Math.floor(Math.random() * (xMax – xMin) + xMin);
      _y = Math.floor(Math.random() * (yMax – yMin) + yMin);
      
      //Select a random direction to start moving this clip in.
      xVel = Math.floor(Math.random() * 12) – 5;
      yVel = Math.floor(Math.random() * 12) – 5;
      
      // Dynamically make the onReleaseOuside method the same as the 
      // onRelease method.
      onReleaseOutside = onRelease;      
   }
   
   /** 
    * The onPress method is a movie clip event handler that is called 
    * whenever the user on this clip with the mouse. The method 
    * starts the dragging process so the clip will follow the mouse 
    * and adjusts its color.
    */
   function onPress() {
      startDrag(true);
      dragging = true;
      // Make the clip black to show it has been captured.
      gColor.setRGB(0x000000); 
   }
   
   /**
    * The onEnterFrame method is called whenever an EnterFrame
    * event is sent to this movie clip subclass. If the clip is not 
    * being dragged, the next position of the clip is calculated
    * making sure to keep it within bounds and then the clip
    * is moved to that position.
    */
   function onEnterFrame() {
      if (dragging) 
         return;
      }
      var nextX = _x + xVel;
      var nextY = _y + yVel;
      if (nextX < xMin) {
         xVel *= –1;
         nextX = xMin + (xMin – nextX);
      } else if (nextX > xMax) {
         xVel *= –1;
         nextX = xMax – (nextX – xMax);
      }
      if (nextY < yMin) {
         yVel *= –1;
         nextY = yMin + (yMin – nextY);
      } else if (nextY > yMax) {
         yVel *= –1;
         nextY = yMax – (nextY – yMax);
      }
      _x = nextX;
      _y = nextY;
   }
   
   /**
    * When the player releases the mouse button this movie clip event 
    * handler is called. If the clip is dropped on its target clip
    * a hit is recorded using the scoreKeeper object and the puzzle 
    * piece disposes of itself. Otherwise the puzzle piece goes back
    * to moving inside the bounceBox.
    */
   function onRelease() {
      stopDrag();
      if (hitTest(targetClip)) {
         targetClip.fadeOut();
         scoreKeeper.recordHit();
		 this.removeMovieClip(); // Compiler bug – must use this.
      } else {
         gColor.setRGB(0x443377); // Make the clip a grey/blue color.
         dragging = false;
      }
   }
}
    

Note: In the previous version of this tutorial, I used onMouseDown and onMouseUp events to see if the player clicked or released the PuzzlePiece. This class uses the onPress, onRelease, and onReleaseOutside events instead, which simplifies the code.

Keeping Score

In the original version of this game, code on the movie Timeline kept track of the number of puzzle pieces that players successfully dropped on each drop zone as well as the time it took to play the game. In this version of the game, those functions now live inside an ActionScript class named ScoreKeeper. One scoreKeeper object is created at the start of a game and used to record successful puzzle piece drops and game time. Here is the complete code for the ScoreKeeper class. It's a simple class that does not extend any other class:

/**
 * The ScoreKeeper class is designed to keep track of how
 * long a game has taken to the play, and the number of 
 * successful hits. The recordHit method is called by PuzzlePiece
 * movie clips when they are dropped on the correct DropZone.
 * The constructor of this class must be passed:
 *   1. a reference to the timeline the game is on and
 *   2. the number of PuzzlePieces (or shapes) in the game.
 *
 * Version: 1
 * Author: Brian Lesser
 */

class ScoreKeeper{
   var hits:Number = 0;          // number of successful hits (puzzle piece drops)
   var nShapes:Number;           // number of Puzzle Pieces
   var startTime:Number;         // start time in milliseconds from getTimer()
   var endTime:Number;           // end time in milliseconds 
   var scoring:Boolean = true;   // flag that indicates if the game is being played
   var root:MovieClip;           // reference to the game timeline 
                                 // – normally level0 or _root
   
   /** ScoreKeeper constructor function */
   function ScoreKeeper(r, n){
      root = r;
      nShapes = n;
      startTime = getTimer();
   }
   
   /** 
    * recordHit is called to record a hit in the game. 
    * If the number of hits equals the number of shapes 
    * the game is over so the root movieclip reference is 
    * sent ahead to the EndGame frame.
    */
   function recordHit(){
      if (scoring) hits++;
      if (hits == nShapes){
         root.gotoAndPlay("EndGame");
      }
   }
   
   /** stopScoring gets the end time of the game and makes 
    *  further scoring impossible.
    */
   function stopScoring(){
      endTime = getTimer(); 
      scoring = false;
   }

   /** getScore returns a text string with the score in it.*/
   function getScore(){
      var totalTime = (endTime – startTime)/1000;
      // If they have placed all the pieces say thanks and tell them how long.
      if (hits == nShapes){
         return "Thanks for playing.\n\nIt took you " + 
                totalTime + 
                " seconds \nto play the game."
      }
      // If they didn't place all the pieces send a different message.
      else{
         var score = Math.round(hits/nShapes * 100);
         return "Thanks for playing.\n\nIt took you " + 
                totalTime + 
                " seconds \nto play " +  score + "% of the game."
      }
   }
}
    

Multiple States

So far every line of code in this tutorial has been part of a class definition. In fact, the vast majority of code appears in the three class files, PuzzlePiece.as, DropZone.as, and ScoreKeeper.as. The only other code in the game appears on the Actions layer of the main Timeline. This code handles the setup of the three states of the game. Each game state is associated with a label in the main Timeline (see Figure 4). The game is initialized on the Welcome frames, played on the PlayGame frames, and completed on the EndGame frames.

Each label in the movie Timeline label identifies a different state in the game.

Figure 4. Each label in the movie Timeline label identifies a different state in the game.

The unique code required for each state is on the first frame for that state in the Actions layer. To keep the playhead from running from one state to another, stop() is called once in each state. When the game must change state, a gotoAndPlay() is called.

The Welcome Frame: The welcome screen contains a text field with player instructions and a navigation button. It also contains the following code:

/**
 * fisher_yates_shuffle as adapted from the Perl Cookbook,
 * by Christiansen and Torkington, Published by O'Reilly
 * pass this array a reference to a function. For example:
 *    array = new Array('hi', 'bye', 'hello', 'goodbye');
 *    fisher_yates_shuffle(array);
 * and the function will pseudo randomize the elements of the
 * array in place.
 **/
function fisher_yates_shuffle(ar){
   var i, j 
   var temp
   for (i = ar.length – 1; i > 0; i––){
      j = Math.floor(Math.random() * (i + 1))
      if (i == j) continue
      temp = ar[i];
      ar[i] = ar[j];
      ar[j] = temp;
   }
}

// Create an arrray of shape numbers that can be randomized later
// in order to randomize the position of the shapes in the drop zone.
_global.shapeNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

// Initialize the navigation button.
label = "Start the Game!";
navButton.onRelease = function(){
   gotoAndPlay("PlayGame");
}
    

This code declares a global function to randomize the numbers in the shapeNumbers array and provides the navigation button with a label and code to execute if it is released. There isn't much to this code; the real action happens when the player presses the navButton and the playhead moves to the PlayGame frame.

The PlayGame Frame: Starting the game is the most complex part of the Timeline code. The complete code appears below. After a ScoreKeeper object is created to keep track of scoring, the game shapes themselves are randomly attached to the movie. To randomize the shapes, the numbers 1 through 13 are shuffled inside the shapeNumbers array. Following the shuffle the rest of the work is done inside a for loop. In each loop a DropZone clip is attached to the movie and passed one of the numbers in the array. Then a PuzzlePiece clip is attached and initialized with the same number. The DropZone clip is always created first so that a reference to it can be passed into the initObject of the PuzzlePiece clip. That is how each puzzle piece knows which drop zone it matches. Take a close look at the for loop in the code below to see how this works. Each DropZone clip is stored in the mc variable that is used later to initialize each PuzzlePiece. You may also want to check the ScoreKeeper constructor function again. Notice that it records the time when the game starts.

Aside from some variables to keep track of things, the important part of this code is the loop that creates the puzzle pieces and drop zones. Each puzzle piece is named p1, p2, p3 through p13 and each is given a number property with a value in the range of 1 to 13, which happens to be the same number of the graphic symbols in the library. There are also 13 DropZone movie clips created, named d1 through d13, with an initial _x and _y position and a number property that contains the number of the correct graphic symbol to load:

// Create a new score keeper object replacing the old one if one already exists.
_global.scoreKeeper = new ScoreKeeper(this, shapeNumbers.length);

// Shuffle the clip numbers in the shapeNumbers array so the clips
// are positioned randomly in the drop zone area.
fisher_yates_shuffle(shapeNumbers);

// Determine the _x position of the left-most clip
firstClipPosition = bounceBox_mc._x + 20;

var mc; // Variable to hold clip references.

// Create all the DropZone and PuzzlePiece clips in a loop.
for (i=0; i <shapeNumbers.length; i++){
   var gNumber = shapeNumbers[i];
   mc = attachMovie("DropZone", "d" + i, i + 200, 
                    {_x: i * 38 + firstClipPosition, 
                     _y: 336, 
                     gNumber: gNumber});
   attachMovie("PuzzlePiece",  "p" + i, i + 300, 
               {targetClip: mc, 
                bounceBox: bounceBox_mc, 
                gNumber:  gNumber, 
                scoreKeeper: scoreKeeper});
   
}

// Setup the navigation button.
label = "I Quit!";
navButton.onRelease = function(){
   // Remove any left over Puzzle Piece clips.
   for (var i = 0; i < shapeNumbers.length; i++){
      eval("p" + i).removeMovieClip();
   }
   gotoAndPlay("EndGame");
}
    

The EndGame Frame: The game can end in two ways. Each time a puzzle piece is dropped on its target drop zone it calls the scorekeeper.recordHit() method. If the scorekeeper determines that all the pieces have been used up it sends the game's playhead to the EndGame frame. Similarly, if the player presses the navButton in the PlayGame frames it sends the playhead to the EndGame frame. When the playhead arrives at the EndGame frame, the navButton is given a label "Play again!", the game is stopped by calling scoreKeeper.stopGame(), and an end-of-game message appears. Here is the complete code from the EndGame frame:

// Tell the score keeper the game is over.
scoreKeeper.stopScoring();

// Report the results to the user.
message_txt.text = scoreKeeper.getScore();

// Setup the navigation button for this frame of the movie.
label = "Play again!";
navButton.onRelease = function(){
   gotoAndPlay("PlayGame");
}
    

That's it to the grab-and-match puzzle. Go ahead, play the game. It's not as easy as it looks!

There is a nice parallel between movie clip symbols/instances and ActionScript classes/objects. Movie clip symbols in the library are much like ActionScript classes: They act as a template that defines the common characteristics of each movie clip. Movie clip instances are much like ActionScript objects: There can be many of them—each based on the original symbol—but with different characteristics, depending on how they were initialized and on what happens to them as the movie plays.

The difference between them is that ActionScript classes can provide predefined behaviors for ActionScript objects and, when those objects extend the MovieClip class, can also provide predefined behaviors for a movie clip symbol. Without ActionScript classes it is difficult to provide predefined behaviors in movie clip symbols.

Macromedia Flash MX first bridged the gap between these two parallel worlds. ActionScript 2.0 provides a simpler and more elegant way to write classes that extend movie clip symbols.


About the author

Brian Lesser works at Ryerson University in Computing and Communications Services, where he has the ungainly title of Assistant Director, Teaching and Technology Support. Brian also teaches at Ryerson's School of Image Arts, contributed to Macromedia Flash MX ActionScript Bible (Hungry Minds, 2002), and coauthored Programming Flash Communication Server (forthcoming from O'Reilly & Associates).